package com.qiqu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiqu.Vo.ArticleVo;
import com.qiqu.Vo.CommentsVo;
import com.qiqu.dao.mapper.CommentsCustom;
import com.qiqu.entity.Comments;
import com.qiqu.dao.CommentsDao;
import com.qiqu.service.CommentsService;
import com.qiqu.utils.PagedResult;
import com.qiqu.utils.TimeAgoUtils;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service("commentsService")
public class CommentsServiceImpl implements CommentsService {
    @Resource
    private CommentsDao commentsDao;
    @Resource
    private Sid sid;
    @Resource
    private CommentsCustom commentsCustom;


    @Override
    public Comments queryById(String id) {
        return null;
    }

    @Override
    public boolean addComments(Comments comments) {
        comments.setId(sid.nextShort());
        comments.setCreateTime(new Date());
        return  commentsDao.insert(comments)>0;
    }


    @Override
    public boolean deleteById(String id) {
        Example c = new Example(Comments.class);
        Example.Criteria criteria = c.createCriteria();
        criteria.andEqualTo("id",id);
        return commentsDao.deleteByExample(c)>0;
    }

    @Override
    public Integer totalComments() {
        return commentsDao.totalComments();
    }

    @Override
    public Integer articleComments(String articleId) {
        return commentsDao.articleComments(articleId);
    }

    @Override
    public PagedResult getComments(String articleId, Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<CommentsVo> commentsVos = commentsCustom.queryArticleComments(articleId);
        for(CommentsVo commentsVo:commentsVos){
            commentsVo.setTimeDesc(TimeAgoUtils.format(commentsVo.getCreateTime()));
        }
        PageInfo<CommentsVo> pageList=new PageInfo<>(commentsVos);
        PagedResult pagedResult =new PagedResult();
        pagedResult.setPage(page);
        pagedResult.setTotal(pageList.getPages());
        pagedResult.setRows(commentsVos);
        pagedResult.setRecords(pageList.getTotal());
        return pagedResult;
    }
}